package com.my.spring.framework.webmvc.servlet;

import java.io.File;
import java.util.Locale;

public class MyViewResolver {
    private static final String DEFAULT_TEMPLATE_SUFFIX = ".html";
    private File templateRootDir;

    public MyViewResolver(String templateRoot) {
        String templateRootPath = getClass().getClassLoader().getResource(templateRoot).getFile();
        templateRootDir = new File(templateRootPath);
    }

    public MyView resolveViewName(String viewName, Locale locale) throws Exception{
        if (viewName == null || "".equals(viewName.trim())) {
            return null;
        }
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ? viewName : viewName + DEFAULT_TEMPLATE_SUFFIX;
        String fullName = (templateRootDir.getPath() + "/" + viewName).replaceAll("/+", "/");
        return new MyView(new File(fullName));
    }
}
